package com.chx.three.fxgood.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chx.three.fxgood.R;
import com.chx.three.fxgood.fragments.CNewsFragment;
import com.chx.three.fxgood.fragments.CPictureFragment;
import com.chx.three.fxgood.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * fragment中viewPager和scrollView中标题的联动
 */
public class LinkageLayout extends RelativeLayout implements View.OnClickListener {
    //当前指定位置
    int index;
    private Context mContext;
    //存放标题
    private String[] mTitles=new String[]{"新闻","照片","商城","游戏","视频","短歌","故事","MV","SNS","贴吧","粉丝","通告","照片PK"};
    //存放上方layout
    private LinearLayout[] mTitleLayouts;
    //存放上放过标题
    private TextView[] mTitleViews;
    //存放上方底部的指示
    private View[] mViews;
    //viewPager
    private ViewPager viewPager;
    //fragment
    private List<Fragment> fragments;
    private SelectHorizontalScrollView scrollView;
    //是否是第一次加载
    private boolean hasFirst;
    //每一个item的宽度
    int mItemWidth;
    FragmentActivity activity;
    public LinkageLayout(Context context) {
        this(context, null);
    }

    public LinkageLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LinkageLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext=context;
        if(!(context instanceof FragmentActivity)){
            throw new IllegalArgumentException("context must extends FragmentActivity");
        }
        activity=(FragmentActivity)context;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(!hasFirst){
            scrollView = (SelectHorizontalScrollView)getChildAt(0);
            viewPager=(ViewPager)getChildAt(2);
            setFragments();
            createTitle();
            hasFirst=true;
        }
    }

    /**
     * 设置fragment
     */
    public void setFragments(){
        fragments=new ArrayList<>();
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());
        fragments.add(new CPictureFragment());
        fragments.add(new CNewsFragment());

        viewPager.setAdapter(new FragmentPagerAdapter(activity.getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                    return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index=position;
                setTitleBottomView();
                setScrollTo();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 创建标题栏，在此之前，必须先配置title数据
     */
    private void createTitle(){
        mTitleLayouts=new LinearLayout[mTitles.length];
        mTitleViews=new TextView[mTitles.length];
        mViews=new View[mTitles.length];
        if(mTitles==null){
            throw new IllegalArgumentException("must config title data");
        }
        //整个title布局
        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
        //字体布局
        LinearLayout.LayoutParams txtParams =
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        txtParams.topMargin= DensityUtil.dip2px(mContext,8);
        txtParams.bottomMargin= DensityUtil.dip2px(mContext,6);
        txtParams.leftMargin=DensityUtil.dip2px(mContext,15);
        txtParams.rightMargin=DensityUtil.dip2px(mContext,15);
        //底部指示条
        LinearLayout.LayoutParams viewParams =
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        DensityUtil.dip2px(mContext,2));
        for (int i = 0; i < mTitles.length; i++) {
            LinearLayout layout=new LinearLayout(mContext);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setGravity(CENTER_IN_PARENT);

            layout.setLayoutParams(params);

            TextView textView=new TextView(mContext);
            textView.setLayoutParams(txtParams);
            textView.setGravity(CENTER_IN_PARENT);
            textView.setTextSize(18);
            textView.setTextColor(Color.BLACK);
            textView.setText(mTitles[i]);
            textView.setTag(i);
            textView.setOnClickListener(this);

            View view=new View(mContext);
            view.setBackgroundColor(Color.parseColor("#ffdd80c5"));
            view.setLayoutParams(viewParams);
            if(i==index){
                view.setVisibility(View.VISIBLE);
            }else{
                view.setVisibility(View.GONE);
            }

            mItemWidth=textView.getWidth();

            mTitleViews[i]=textView;
            mViews[i]=view;
            layout.addView(textView);
            layout.addView(view);
            layout.setTag(i);
            mTitleLayouts[i]=layout;
            scrollView.getLayout().addView(layout);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }


    /**
     * 设置title的点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        if(v.getTag()==null){
            return;
        }
        if(v.getTag() instanceof Integer){
            index=(int)v.getTag();

            setScrollTo();
        }
    }

    private void setScrollTo() {
        int x=0;
        for (int i = 0; i < index; i++) {
            x+=mTitleLayouts[i].getWidth();
        }
        scrollView.scrollTo(x,0);
        setTitleBottomView();
        if(fragments.size()>=index){
            viewPager.setCurrentItem(index);
        }else{
            viewPager.setCurrentItem(fragments.size());
        }
    }

    /**
     * 设置底部显示与隐藏
     */
   private void setTitleBottomView(){
       for (int i = 0; i < mTitles.length; i++) {
            if(i==index){
                mTitleViews[i].setTextColor(Color.RED);
                mViews[i].setVisibility(View.VISIBLE);

            }else{
                mTitleViews[i].setTextColor(Color.BLACK);
                mViews[i].setVisibility(View.GONE);
            }
       }
   }
}
